﻿using EnvCheck.Models;
using EnvCheck.Services;
using EnvCheck.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EnvCheck.View.Existing
{
    public class ReqSatisfactionViewModel :
        BaseViewModel
    {
        private string _appVersion="";

        public string AppVersion { 
            get => _appVersion; 
            set { 
                _appVersion = value;
                GlobalViewModel.ModelByReqVersion.TryAdd(AppVersion, []);
                VersionName = value;
                var requiredApps = DatabaseService.GetAllRequiredApps(AppVersion);
                AppReqSatisfactionStatuses.Clear();
                foreach (var req in requiredApps)
                {
                    GlobalViewModel.ModelByReqVersion[AppVersion].TryAdd(req.Name,req);
                    OnPropertyChanged(nameof(AppReqSatisfactionStatuses));
                }
                InstalledAppService.AsyncLoadInstalledApps(this);
            } 
        }

        public ObservableCollection<AppReqSatisfactionStatus> AppReqSatisfactionStatuses { 
            get {
                return new([.. GlobalViewModel.ModelByReqVersion[AppVersion].Values]);
            }
        }

        public override void Receive(string name, string version)
        {
            VersionCompareHelper.RegularizeAppName(ref name, version);
            if (GlobalViewModel.ModelByReqVersion.TryGetValue(AppVersion, out var dict) && dict != null)
            {
                if (dict.TryGetValue(name, out var value))
                {
                    value.InstalledVersion = version;
                }
            }
        }

        public override void ReportProgress(int current, int total)
        {

        }
    }
}
